package com.zmytest.aop;

import com.zmytest.annotation.CreateCookie;
import com.zmytest.common.ConfigStringAnalyzer;
import com.zmytest.service.CookieService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * Created on 2018/12/14.
 *
 * @author zhangmingyu
 */
@Aspect
@Component
@Slf4j
public class CreateCookieAspect {

    @Autowired
    private CookieService cookieService;

    @Pointcut("@annotation(com.zmytest.annotation.CreateCookie)")
    public void pointCut(){}

    @AfterReturning(returning = "result",pointcut = "pointCut() && @annotation(createCookie)")
    public void doAfter(JoinPoint joinPoint, Object result, CreateCookie createCookie){
        String flag = createCookie.flag();
        if (ObjectUtils.isEmpty(flag)) {
            createCookie(joinPoint, result, createCookie);
            return;
        }
        //获取配置的flag真实值。
        Object flagValue = ConfigStringAnalyzer.getValue(joinPoint,result,flag);
        //获取配置的flagResult
        String flagConfigResult = createCookie.flagResult();
        Object condition = Boolean.TRUE;
        if (!ObjectUtils.isEmpty(flagConfigResult)) {
            condition = ConfigStringAnalyzer.getValue(joinPoint,result,flagConfigResult);
        }
        if (condition.equals(flagValue)){
            createCookie(joinPoint,result,createCookie);
        }else {
            log.info("不满足创建session条件，不创建。");
        }
    }

    private void createCookie(JoinPoint joinPoint, Object result, CreateCookie createCookie){
        String configKey = createCookie.key();
        String configValue = createCookie.value();
        String key = ConfigStringAnalyzer.getValue(joinPoint,result,configKey).toString();
        String value = ConfigStringAnalyzer.getValue(joinPoint,result,configValue).toString();
        log.info("create cookie key={},value={}",key,value);
        cookieService.create(key,value);
    }
}
